/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.policysyn;

import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Dpiendpointbean;
import cn.net.greenet.db.bean.Messageincominglog;
import cn.net.greenet.db.bean.Policyrepositoryinstance;
import cn.net.greenet.db.bean.Rvcheckstatus;
import cn.net.greenet.db.bean.Versionreported;
import cn.net.greenet.db.bean.VersionreportedId;
import com.ambimmort.umessage.uc.incoming.xC2;
import com.ambimmort.umessage.util.HexUtil;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author Administrator
 */
@WebServlet(name = "cn.net.greenet.policysyn.GetReportedVersion", urlPatterns = {"/policy/synchronization/getReportedVersion"})
public class GetReportedVersion extends HttpServlet {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String dpiId = request.getParameter("dpiId");
        PrintWriter out = response.getWriter();
        SessionFactory sf = HibernateUtil.getSessionFactory();
        sf.getCache().evictEntityRegion(Messageincominglog.class);
        sf.getCache().evictEntityRegion(Versionreported.class);
        Session session = sf.openSession();
        Object rvcheckstatusObject = session.get(Rvcheckstatus.class, Integer.parseInt(dpiId));

        long lastCheckTime = 946656000000l; // 2000年1月1日 00:00:00
        if (rvcheckstatusObject == null) {
            Rvcheckstatus status = new Rvcheckstatus(Integer.parseInt(dpiId), new Date(System.currentTimeMillis()));
            Transaction tx = null;
            try {
                tx = session.beginTransaction();
                session.save(status);
                tx.commit();
            } catch (Exception e) {
                e.printStackTrace();
                tx.rollback();
            }
        } else {
            Rvcheckstatus status = (Rvcheckstatus) rvcheckstatusObject;
            lastCheckTime = status.getLastCheckTime().getTime();
        }

        Date lastTimePtr = new Date(lastCheckTime);

        try {
            Versionreported bean = null;
            Dpiendpointbean dpiBean = (Dpiendpointbean) session.get(Dpiendpointbean.class, Integer.parseInt(dpiId));
            Map<String, Integer> map = new HashMap<String, Integer>();
            Policyrepositoryinstance priPtr = null;
            for (Object piObj : dpiBean.getPolicyrepositoryinstances()) {
                priPtr = (Policyrepositoryinstance) piObj;
                map.put(priPtr.getPolicyrepositorytype().getMessageType(), priPtr.getId());

            }

            System.out.println("==>[Function GetReportedVersion]");
            System.out.println("=>DPI Configured map: " + dpiBean.getName());
            System.out.println("=>" + map.toString());
            Messageincominglog log = null;
            Query q1 = session.createQuery("SELECT log FROM Messageincominglog AS log where log.dpiendpointbean.id=:dpiId and log.messageType=:messageType and log.time > :lastCheckTime ORDER BY log.time");
            q1.setParameter("messageType", "0xC2");
            q1.setParameter("dpiId", dpiBean.getId());
            q1.setParameter("lastCheckTime", lastTimePtr);
            List c2log = q1.list();

            if (!c2log.isEmpty()) {
                for (Object logObj : c2log) {
                    log = (Messageincominglog) logObj;
                    Transaction tx = null;

                    xC2 c2 = new xC2();
                    try {
                        c2.parseBinary(log.getPacket());
                    } catch (Exception e) {
                        System.out.println("==>[Packet Exception][IN][C2][LOG:" + log.getId() + "][" + dpiBean.getName() + "][" + dpiBean.getMasterIp() + "]");
                        continue;
                    }
                    System.out.println("=>logid=" + log.getId());
                    System.out.println("=>parsedC2=" + c2.getPolicys().toString());
                    String msgType = null;
                    for (xC2.Message m : c2.getPolicys()) {
                        msgType = "0x" + HexUtil.getHex(m.getMessageType().toByte());
                        System.out.println("=>processing:logid:" + log.getId() + ",msgType:" + msgType);
                        if (map.containsKey(msgType)) {
                            try {
                                tx = session.beginTransaction();
                                Versionreported vr = new Versionreported();
                                vr.setDpiendpointbean(dpiBean);
                                vr.setPolicyrepositoryinstance((Policyrepositoryinstance) session.get(Policyrepositoryinstance.class, map.get(msgType)));
                                VersionreportedId vid = new VersionreportedId(Integer.parseInt(dpiId), map.get(msgType));
                                vr.setId(vid);
                                vr.setMessageSerialNo(m.getMessageSerialNo().toLong());
                                vr.setReportTime(log.getTime());
                                session.saveOrUpdate(vr);
                                System.out.println("=>saveOrUpdated:<" + vr.getId().getDpiendPointBeanId() + "," + vr.getId().getPolicyRepositoryInstanceId() + ">");
                                session.createQuery("update Rvcheckstatus r set r.lastCheckTime=:time where r.dpiId=:dpiId").setParameter("time", new Date(System.currentTimeMillis())).setParameter("dpiId", Integer.parseInt(dpiId)).executeUpdate();
                                tx.commit();
                                session.evict(vr);
                            } catch (Exception e) {
                                e.printStackTrace();
                                tx.rollback();
                            }
                        }
                    }

                }
            }

            JSONObject config = new JSONObject();
            Policyrepositoryinstance pri = null;
            session.refresh(dpiBean);
            for (Object piObj : dpiBean.getPolicyrepositoryinstances()) {
                pri = (Policyrepositoryinstance) piObj;
                JSONObject in = new JSONObject();
                in.put("version", "-1");
                in.put("time", "-");
                in.put("configured", true);
                config.put(pri.getPolicyrepositorytype().getMessageType(), in);
            }
            System.out.println("=>configuredJSON=" + config.toString(4));

            Query q = session.createQuery("SELECT reported FROM Versionreported AS reported where reported.dpiendpointbean.id=:dpiId");
            q.setParameter("dpiId", dpiBean.getId());
            java.util.List l = q.list();
            String messageType = null;
            for (Object o : l) {
                bean = (Versionreported) o;
                messageType = bean.getPolicyrepositoryinstance().getPolicyrepositorytype().getMessageType();
                if (config.has(messageType)) {
                    JSONObject in = config.getJSONObject(messageType);
                    in.put("version", bean.getMessageSerialNo());
                    in.put("time", sdf.format(bean.getReportTime()));
                } else {
                    JSONObject in = new JSONObject();
                    in.put("version", bean.getMessageSerialNo());
                    in.put("time", sdf.format(bean.getReportTime()));
                    in.put("configured", false);
                    config.put(messageType, in);
                }
            }
            System.out.println("=>finalJSON=" + config.toString(4));
            try {
                out.println(config);
            } catch (Exception e) {
                out.println("{}");
            }

        } catch (Exception e) {
            e.printStackTrace();
            out.println("{}");
        } finally {
            out.close();
            session.close();
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
